package util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: gaotianlin
 * Date: 13-7-22
 * Time: 下午2:56
 * To change this template use File | Settings | File Templates.
 */
public class JsonUtil {
	private static ObjectMapper mapper = new ObjectMapper();
	
	private static final Logger logger = LoggerFactory
            .getLogger(JsonUtil.class);

	static{
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);//设置序列化配置，为null的属性不加入到json中
		mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);//兼容单引号 但单引号不属于json标准 不建议使用
	}
	/**
	 * 将对象转换成json字符串,如果转换失败则返回null
	 * @author zhaoyunxiao
	 * @param o 需要转换为json的对象
	 * @return String 转换后的json字符串
	 *
	 *
	 * */
    public static String write2JsonStr(Object o){
    	String jsonStr = "";
    	try {
    		jsonStr = mapper.writeValueAsString(o);
		} catch (JsonProcessingException e) {
            logger.error("write2JsonStr() exception: " + e.getMessage());
		}
		return jsonStr;
    }

    /**
     * 将json转换为对象 如果对象模版为内部类会出现问题，所以不要使用内部类
     * @author zhaoyunxiao
     * @param json 要转换的json
     * @return 转换成的目标对象，如果转换失败返回null
     * */
    public static Object json2Object(String json,Class<?> clazz){
    	try {
			 return mapper.readValue(json,clazz);
		} catch (JsonParseException e) {
            logger.error("json2Object() parseException: " + e.getMessage());
		} catch (JsonMappingException e) {
            logger.error("json2Object() mappingException: " + e.getMessage());
		} catch (IOException e) {
            logger.error("json2Object() IOException: " + e.getMessage());
		}
    	return null;
    }

    /**
     * 将json字符串转换为Map
     * @author zhaoyunxiao
     * @param  json 需要转换为Map的json字符串 {}开头结尾的
     * @return 转换后的map 如果转换失败返回null
     * */
    @SuppressWarnings("unchecked")
	public static Map<String,Object> json2Map(String json){
    	try {
    		if(StringUtils.isBlank(json)||json.startsWith("<")) {
                return new HashMap<String,Object>() ;
    		}
            if(json.contains(":,")){
                json=json.replaceAll(":,",":null,");
            }
            return mapper.readValue(json,Map.class);
		} catch (JsonParseException e) {
            logger.error("json2Map(), 出错的json内容：" + json + " ,JsonParseException: " + e.getMessage());
		} catch (JsonMappingException e) {
            logger.error("json2Map(), 出错的json内容：" + json + " ,JsonMappingException: " + e.getMessage());
		} catch (IOException e) {
            logger.error("json2Map(), 出错的json内容为：" + json + " ,IOException: " + e.getMessage());
		}
        return new HashMap<String,Object>() ;
    }
    /**
     * 将json数组转换为List<Map<String,Object>> json数组格式[{},{}]
     * @author zhaoyunxiao
     * @return 转换后的列表   如果转换失败返回null
     * */
    @SuppressWarnings("unchecked")
	public static List<Map<String,Object>> jsonArray2List(String jsonArray){
        try {
			return mapper.readValue(jsonArray, List.class);
		} catch (JsonParseException e) {
            logger.error("jsonArray2List() exception, 异常字符串: " + jsonArray, e);
		} catch (JsonMappingException e) {
            logger.error("jsonArray2List() exception, 异常字符串: " + jsonArray, e);
		} catch (IOException e) {
            logger.error("jsonArray2List() exception",e);
		}
        return new ArrayList<Map<String,Object>>();
    }

    /**
     * 将json数组转换为List<Map<String,Object>> json数组格式[{},{}]
     * @author zhaoyunxiao
     * @return 转换后的列表   如果转换失败返回null
     * */
    @SuppressWarnings("unchecked")
	public static List<Map<String,Object>> jsonArray2List(String jsonArray,String keyword){
        try {
			return mapper.readValue(jsonArray, List.class);
		} catch (JsonParseException e) {
            logger.error("JsonUtil exception, keyword: "+keyword+", 异常字符串: " + jsonArray, e);
		} catch (JsonMappingException e) {
            logger.error("JsonUtil exception, keyword: "+keyword+", 异常字符串: " + jsonArray, e);
		} catch (IOException e) {
            logger.error("JsonUtil exception",e);
		}
        return new ArrayList<Map<String,Object>>();
    }

    public static Map<String,Object> json2MapAllowSpecial(String json){
        try {
            if(StringUtils.isBlank(json)||json.startsWith("<")) {
                return new HashMap<String,Object>() ;
            }
            if(json.contains(":,")){
                json=json.replaceAll(":,",":null,");
            }
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
            return mapper.readValue(json,Map.class);
        } catch (JsonParseException e) {
            logger.error("json2Map(), 出错的json内容：" + json + " ,JsonParseException: " + e.getMessage());
        } catch (JsonMappingException e) {
            logger.error("json2Map(), 出错的json内容：" + json + " ,JsonMappingException: " + e.getMessage());
        } catch (IOException e) {
            logger.error("json2Map(), 出错的json内容为：" + json + " ,IOException: " + e.getMessage());
        }
        return new HashMap<String,Object>() ;
    }

    /**
     * 如果JSON字符串为Null或"null"字符串,返回Null.
     * 如果JSON字符串为"[]",返回空集合.
     * @param jsonString
     * @param clazz
     */
    public static <T> T fromJson(String jsonString, Class<T> clazz) {
        if (org.apache.commons.lang.StringUtils.isBlank(jsonString)) {
            return null;
        }
        try {
            return (T) mapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            logger.error("parse json string error:" + jsonString, e);
        }
        return null;
    }


/*   public static void main(String[] args) {
    	String json = "{'name':'zhaoyunxiao','age':'12'}";
    	String jsonArray = "[{\"name\":\"zhaoyunxiao\",\"age\":\"12\"},{\"name\":\"dengzhengping\",\"age\":\"13\"}]";
    	System.out.println(json);
    	TestPerson p = (TestPerson)json2Object(json, TestPerson.class);
    	System.out.println(p.getName());
    	Map<String,Object> res = json2Map(json);
    	System.out.println(res);
    	List<Map<String,Object>> l = jsonArray2List(jsonArray);
    	System.out.println(l);

	}*/
    
    public static void main(String[] args) {
		String json = "{\"name\":\"wangfei\"}";
		
		Stu s = JsonUtil.fromJson(json, Stu.class);
		
		System.out.println(s.name + "," + s.age);
		
		String path = "/asd/dd/aa";
		System.out.println(path.substring(path.lastIndexOf("/") + 1,path.length()));
	}
}

class Stu{
	String name;
	String age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	
	
}
